//
//  LimitTextField.swift
//  LogisticsDriver
//
//  Created by pengpai on 2020/2/3.
//  Copyright © 2020 qiluys. All rights reserved.
// natsu test access right

import UIKit

@IBDesignable
public class LimitTextField: UITextField {
    
    public var inputLimitType: LimitTextFieldInputRegularType {
        set{
            _inputLimitType = newValue
            limitInputDelegate.inputLimitType = inputLimitType
            self.delegate = limitInputDelegate
            self.keyboardType = inputLimitType.keyboardType()
        }
        get{
            return _inputLimitType
        }
    }
    private var _inputLimitType: LimitTextFieldInputRegularType = LimitTextFieldInputRegularType.RegularNone

    private var limitInputDelegate = LimitTextFieldDelegate()
    
    //MARK: param
    
    /// 长度限制回调
    public var operationLengthLimit: Int? {
        willSet {
            limitInputDelegate.operationLengthLimit = newValue
        }
    }
    /// 是否大小写回调
    public var operationUppercasedLimit: Bool? {
        willSet {
            limitInputDelegate.operationUppercasedLimit = newValue
        }
    }
    /// 自定义操作回调
    public var operationCustomClosure:((_ lastOperationString: String, _ newString: String)->String)? {
        willSet {
            limitInputDelegate.operationCustomClosure = newValue
        }
    }
    /// 完成输入回调
    public var completeTextClosure:((_ text: String)->Void)? {
        willSet {
            limitInputDelegate.completeTextClosure = newValue
        }
    }
    
    /// 操作输入是否受正则控制
    public var operationIsComplyInputLimitType = true {
        willSet {
            limitInputDelegate.operationIsComplyInputLimitType = newValue
        }
    }
    
    /// 删除密码时是否只删除一个字符
    public var operationPasswordDeleteOne: Bool? {
        willSet {
            limitInputDelegate.operationPasswordDeleteOne = newValue
        }
    }
    private lazy var lastOprationStr: String = self.text!
    
}

public class LimitTextFieldDelegate: NSObject, UITextFieldDelegate {
    
    public var inputLimitType: LimitTextFieldInputRegularType = LimitTextFieldInputRegularType.RegularNone
    public var completeTextClosure:((_ text: String)->Void)?
    
    public var operationUppercasedLimit: Bool?
    public var operationLengthLimit: Int?
    public var operationCustomClosure:((_ lastOperationString: String, _ newString: String)->String)?
    public var operationIsComplyInputLimitType = true
    public var operationPasswordDeleteOne: Bool?
    
    public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        //系统拼音输入法的bug
        if ["➋", "➌", "➍", "➎", "➏", "➐", "➑", "➒", "☻"].contains(string) {
            return true
        }
        /// 文本框中已经展示的文字
        let alreadyText = textField.text ?? ""
        /// 已经展示的文字加上新输入的文字 组成即将展示的完整文字
        let newString = (alreadyText as NSString).replacingCharacters(in: range, with: string)
        /// 删除
        if string.isEmpty && newString.count < alreadyText.count {
            if let d = operationPasswordDeleteOne, d, textField.isSecureTextEntry {
                textField.text = newString
                return false
            }
            return true
        }
        
        //只有当即将展示的文字不为空时才需要进行正则表达的判断
        if newString.count > 0{
            /// 获取正则表达式
            let expression = inputLimitType.regularExpression()
            /// 获取匹配结果
            let result = matchStringFormat(matchedStr: newString, withRegex: expression)
            //ps:(newString.length < alreadyText.length)是为了防止意外情况导致的错误信息已录入时， 删除功能无法使用的情况， 就算不符合正则表达式， 删除永远是允许的。
            if result || !operationIsComplyInputLimitType {
                var isControl = false
                // 大小写控制
                if let bool = operationUppercasedLimit {
                    if bool {
                        textField.text = newString.uppercased()
                    }else {
                        textField.text = newString.lowercased()
                    }
                    isControl = true
                }
                if let length = operationLengthLimit, length > 0, length < newString.count {
                    textField.text = String(newString[newString.startIndex..<newString.index(newString.startIndex, offsetBy: length)])
                    isControl = true
                }
                
                if let string = operationCustomClosure?(alreadyText, newString) {
                    textField.text = string
                    isControl = true
                }
                
                if isControl {
                    completeTextClosure?(textField.text!)
                    return false
                }
            }
            if result {
                completeTextClosure?(newString)
            }
            return result
        }
        
        /**
         ps:当即将展示的字符串的字符数量为0时 意味着是删除 所以是允许改变的
         如果此时进行正则表达式的判断 会导致第一个输入的字符无法被删除
         */
        return true
    }
    
    func matchStringFormat(matchedStr:String, withRegex regex:String  )->Bool{
        let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
        
        let result = predicate.evaluate(with: matchedStr)
        
        return result
    }
    
}
//extension LimitTextField: UITextFieldDelegate {
//
//    public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//
//        //系统拼音输入法的bug
//        if ["➋", "➌", "➍", "➎", "➏", "➐", "➑", "➒", "☻"].contains(string) {
//            return true
//        }
//
//        var input = string
//        var regularString = ""
//
//        // 获取正则表达式
//        if let regular = regularLimitCb?() {
//            regularString = regular
//        }
//        if let regularType = regularLimitTypeCb?() {
//            regularString = regularType.regularExpression()
//        }
//        if !regularString.isEmpty {
//            /// 获取匹配结果
//            let result = matchStringFormat(matchedStr: input, withRegex: regularString)
//            if !result { input = "" }
//        }
//
//        // 大小写控制
//        if let bool = operationUppercasedLimit?() {
//            if bool {
//                input = input.uppercased()
//            }else {
//                input = input.lowercased()
//            }
//        }
//
//
//        let tt = NSString(string: self.text!)
//        var count = input.count
//        // length
//        var result = tt.replacingCharacters(in: range, with: input) as NSString
//        let selectedRange = self.selectedRange()
//        if let length = operationLengthLimitCb?(), length > 0 {
//            if result.length > length {
//                result = tt
//                count = 0
//            }
//            //result = result.substring(to: min(result.length, length)) as NSString
//        }
//        var text = result as String
//        self.text = text
//        lastOprationStr = result as String
//        setSelectedRange(NSMakeRange(selectedRange.location+count-range.length, selectedRange.length))
//
//        //operation
//        if let op = customOperationCb {
//            text = op(lastOprationStr, input)
//            self.text = text
//        }
//        completeTextCb?(text)
//        self.sendActions(for: .allEditingEvents)
//        return false
//    }
//
//    func matchStringFormat(matchedStr: String, withRegex regex: String)->Bool{
//        let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
//
//        let result = predicate.evaluate(with: matchedStr)
//
//        return result
//    }
//}

// MARK: - InputLimitTextField
@IBDesignable
/// 单独适配让九宫格拼音输入法能够输入标点符号
public class InputLimitTextField: UITextField {
    
    public var inputLimitType: LimitTextFieldInputRegularType {
        set{
            _inputLimitType = newValue
            limitInputDelegate.inputLimitType = inputLimitType
            self.delegate = limitInputDelegate
            self.keyboardType = inputLimitType.keyboardType()
        }
        get{
            return _inputLimitType
        }
    }
    private var _inputLimitType: LimitTextFieldInputRegularType = LimitTextFieldInputRegularType.RegularNone

    private var limitInputDelegate = InputLimitTextFieldDelegate()

}


class InputLimitTextFieldDelegate: NSObject, UITextFieldDelegate {
    
    var inputLimitType: LimitTextFieldInputRegularType = LimitTextFieldInputRegularType.RegularNone
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        /// 文本框中已经展示的文字
        let alreadyText = textField.text ?? ""
        /// 已经展示的文字加上新输入的文字 组成即将展示的完整文字
        let newString = (alreadyText as NSString).replacingCharacters(in: range, with: string)
        //print("alreadyText-"+alreadyText)
        //print("newString-"+newString)
        
        //--只是适应系统九宫格那些输入，
        if let inputLanguage = textField.textInputMode?.primaryLanguage {
            // 是中文输入
            if inputLanguage == "zh-Hans" {
                
                // 是系统九宫格输入
                if ["➋", "➌", "➍", "➎", "➏", "➐", "➑", "➒", "☻"].contains(string) {
                    return true
                }
                // 系统九宫格输入标点
                if textField.markedTextRange == nil {
                    if ["，", "."].contains(string) {
                        return true
                    }
                }
                else {
                    if string.isEmpty {
                        if newString.count < alreadyText.count { //是删除
                            return true
                        }
                    }else { //是替换
                        let expression = inputLimitType.regularExpression()
                        let result = matchStringFormat(matchedStr: newString, withRegex: expression)
                        if !result {
                            if newString.contains("，") {
                                textField.text = newString.replacingOccurrences(of: "，", with: "")
                            }
                            if newString.contains(".") {
                                textField.text = newString.replacingOccurrences(of: ".", with: "")
                            }
                        }
                        return result
                    }
                }
            }
        }
        //---------------
        
        //只有当即将展示的文字不为空时才需要进行正则表达的判断
        if newString.count > 0{
            /// 获取正则表达式
            let expression = inputLimitType.regularExpression()
            /// 获取匹配结果
            let result = matchStringFormat(matchedStr: newString, withRegex: expression)
            //ps:(newString.length < alreadyText.length)是为了防止意外情况导致的错误信息已录入时， 删除功能无法使用的情况， 就算不符合正则表达式， 删除永远是允许的。
            //系统九宫格---
            if !result {
                if alreadyText.contains("，") {
                    textField.text = alreadyText.replacingOccurrences(of: "，", with: "")
                    let  d = newString.replacingOccurrences(of: "，", with: "")
                    let result = matchStringFormat(matchedStr: d, withRegex: expression)
                    return result
                }
                if alreadyText.contains(".") {
                    textField.text = alreadyText.replacingOccurrences(of: ".", with: "")
                    let  d = newString.replacingOccurrences(of: ".", with: "")
                    let result = matchStringFormat(matchedStr: d, withRegex: expression)
                    return result
                }
            }
            //系统九宫格---
            return result || (newString.count < alreadyText.count)
        }
        textField.sendActions(for: .allEditingEvents)
        /**
         ps:当即将展示的字符串的字符数量为0时 意味着是删除 所以是允许改变的
         如果此时进行正则表达式的判断 会导致第一个输入的字符无法被删除
         */
        return true
    }
    
    func matchStringFormat(matchedStr:String, withRegex regex:String  )->Bool{
        let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
        
        let result = predicate.evaluate(with: matchedStr)
        
        return result
    }
    
}

